//
//  FANStatusViewModel.m
//  Weibo - OC
//
//  Created by user on 16/4/21.
//  Copyright © 2016年 user. All rights reserved.
//

#import "FANStatusViewModel.h"
#import "FANUser.h"
//#import <SDWebImage/SDImageCache.h>
#import <SDWebImage/SDWebImageManager.h>
#import "FANStatusPicInfo.h"
#import <YYText/YYText.h>
#import "FANMatchResult.h"
#import "RegexKitLite.h"
#import "FANEmoticonViewModel.h"
#import <SVProgressHUD/SVProgressHUD.h>

@implementation FANStatusViewModel

- (void)setStatus:(FANStatus *)status{
    
    _status = status;
    
    [self setMemberImage];
    
    [self setretweetText];
    
    [self setSourcetext];
    
    _retweetPictureSize = [self setPictureSize:status.retweeted_status.pic_urls];

    _originalPictureSize = [self setPictureSize:status.pic_urls];
    
    _createDate = [self dealCreatDate:status.created_at];
    
    if (status.text) {
    
        self.originalAttributString = [self attributeText:status.text];

    }else{
        
        self.originalAttributString = [self attributeText:@""];

    }
    
    
}

- (NSAttributedString *)attributeText:(NSString *)text{
    
    
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:text];
    
    NSMutableArray <FANMatchResult *>*results = [NSMutableArray array];
    
    [text enumerateStringsMatchedByRegex:@"\\[[a-zA-Z0-9\\u2E80-\\u9FFF]+\\]" usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
       
        FANMatchResult *result = [[FANMatchResult alloc] init];
        
        result.captureString = *capturedStrings;
        
        result.range = *capturedRanges;
        
        [results addObject:result];
        
    }];
    
    for (FANMatchResult *value in [results reverseObjectEnumerator]) {
        
        if ([[FANEmoticonViewModel sharedEmoticon] emoticonWithChs:value.captureString]) {
            
            FANEmoticon *emoticon = [[FANEmoticonViewModel sharedEmoticon] emoticonWithChs:value.captureString];
            
            UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%@/%@",emoticon.folderName,emoticon.png] inBundle:[FANEmoticonViewModel sharedEmoticon].bundle compatibleWithTraitCollection:nil];
            
            NSMutableAttributedString *attr = [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeScaleAspectFill attachmentSize:CGSizeMake([UIFont systemFontOfSize:15].lineHeight, [UIFont systemFontOfSize:15].lineHeight) alignToFont:[UIFont systemFontOfSize:15] alignment:YYTextVerticalAlignmentCenter];
            
            [attributeString replaceCharactersInRange:value.range withAttributedString:attr];
        }
        
    }
    
    [attributeString addAttribute:NSForegroundColorAttributeName value:[UIColor darkGrayColor] range:NSMakeRange(0, attributeString.length)];
    
    [self addLineColor:@"#[^#]+#" and:attributeString];
    
    [self addLineColor:@"@[\\u4e00-\\u9fa5A-Za-z0-9_\\-]+" and:attributeString];
    
    [self addLineColor:@"([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.',;]*)?" and:attributeString];
    
    [attributeString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, attributeString.length)];
    
    return attributeString;
}

- (void)addLineColor:(NSString *)regex and:(NSMutableAttributedString *)attributeString{
    
    [attributeString.string enumerateStringsMatchedByRegex:regex usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
       
        [attributeString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:80/255.0 green:125/255.0 blue:175/255.0 alpha:1] range:*capturedRanges];
        
        YYTextBorder *border = [[YYTextBorder alloc] init];
        //red: 80/255, green: 125/255, blue: 175/255
        [border setFillColor:[UIColor colorWithRed:80/255.0 green:125/255.0 blue:175/255.0 alpha:1]];
        
        border.insets = UIEdgeInsetsZero;
        
        YYTextHighlight *highlight = [[YYTextHighlight alloc] init];
        
        [highlight setBackgroundBorder:border];
        
        NSString *s = *capturedStrings;
        
        highlight.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
            
            [SVProgressHUD showInfoWithStatus:s];

        };
        
        [attributeString yy_setTextHighlight:highlight range:*capturedRanges];
        
    }];
}

- (NSString *)createText{
    
    return [self dealWeNeedTime:self.createDate];

}

- (NSDate *)dealCreatDate:(NSString *)createAt{
    
    NSDateFormatter *fm = [[NSDateFormatter alloc] init];
    
    fm.locale = [NSLocale localeWithLocaleIdentifier:@"en"];
    
    fm.dateFormat = @"EEE MMM dd HH:mm:ss z yyyy";
    
    NSDate *createDate = [fm dateFromString:createAt];
    
    return createDate;
}

- (NSString *)dealWeNeedTime:(NSDate *)createDate{
    
    NSDateFormatter *fm = [[NSDateFormatter alloc] init];
    
    fm.locale = [NSLocale localeWithLocaleIdentifier:@"en"];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
//    NSLog(@"%@",createDate);
    
    //是今年
    if ([self isDateInThisYear:createDate]) {
        
        if ([calendar isDateInToday:createDate]) {
            
            NSDate *currentDate = [[NSDate alloc] init];
            
            NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:createDate];
            
//            NSLog(@"%lf",timeInterval);
            
            if (timeInterval < 60) {
                
                return @"刚刚";
                
            }else if (timeInterval < 60 * 60){
                
                return [NSString stringWithFormat:@"%d分钟前",(int)timeInterval/60];
                
            }else{
                
                return [NSString stringWithFormat:@"%d小时前",(int)timeInterval/3600];
            }
            
        }else if ([calendar isDateInYesterday:createDate]){
            
            fm.dateFormat = @"HH:mm";
                             
            return [NSString stringWithFormat:@"昨天 %@",[fm stringFromDate:createDate]];
            
        }else{
            
            fm.dateFormat = @"MM-dd HH:mm";
            
            return [fm stringFromDate:createDate];
        }
        
    }else{//往年
        
        fm.dateFormat = @"yyyy-MM-dd HH:mm";
        
        return [fm stringFromDate:createDate];
    }
}

- (BOOL)isDateInThisYear:(NSDate *)createDate{
    
    NSDate *currentDate = [[NSDate alloc] init];
    
    NSDateFormatter *fm = [[NSDateFormatter alloc] init];
    
    fm.locale = [NSLocale localeWithLocaleIdentifier:@"en"];
    
    fm.dateFormat = @"yyyy";
    
    NSString *currentString = [fm stringFromDate:currentDate];
    
    NSString *createString = [fm stringFromDate:createDate];
    
    return [currentString isEqualToString:createString];
    
}

- (void)SinglePictureUpdate{
    
    _retweetPictureSize = [self setSinglePictureSize:self.status.retweeted_status.pic_urls];
    
    _originalPictureSize = [self setSinglePictureSize:self.status.pic_urls];
    
}

- (CGSize)setSinglePictureSize:(NSArray<FANStatusPicInfo *> *)pic_urls{
    
    NSString *imageString = pic_urls.lastObject.thumbnail_pic;
    
    if (imageString == nil) {
        
        return CGSizeZero;
    }
    
    UIImage *image = [[[SDWebImageManager sharedManager] imageCache] imageFromDiskCacheForKey:imageString];
    
    CGFloat scale = [UIScreen mainScreen].scale;
    
    CGSize size = CGSizeMake(image.size.width * scale, image.size.height * scale);
    
    if (size.width < 50){
        
        CGFloat height = 50 / size.width * size.height;
        
        size.width = 50;
        
        size.height = height > 100 ? 100 : height;
    }
    
    return size;
    
}

- (CGSize)setPictureSize:(NSArray *)pic_urls{
    
    NSInteger count = pic_urls.count;
    
    if (count == 0) {
        
        return CGSizeZero;
    }
    
    CGFloat col = (count == 4) ? 2 : (count > 3) ? 3 : count;
    
    CGFloat row = (count - 1)/3 + 1;
    
    CGFloat picWH = FANPictureWH;
    
    CGFloat pictureW = picWH * col + FANPictureMargin * (col - 1);
    
    CGFloat pictureH = picWH * row + FANPictureMargin * (row - 1);
    
    return  CGSizeMake(pictureW, pictureH);
}

- (void)setSourcetext{
    
    // <a href=\"http://app.weibo.com/t/feed/5B6hUc\" rel=\"nofollow\">iPhone 6s Plus</a>

    NSString *source = self.status.source;
    
//    NSLog(@"%@========",source);
    
    if (![source isEqualToString:@""]) {
        
        NSRange startRange = [source rangeOfString:@"\">"];
        
        NSString *str1 = [source substringFromIndex:startRange.location + startRange.length];
        
        NSRange endRange = [str1 rangeOfString:@"</a>"];
        
        NSString *str2 = [str1 substringToIndex:endRange.location];
        
        self.sourceText = [NSString stringWithFormat:@"来自 %@",str2];
    }else{
        
        self.sourceText = @"";
    }
    
}

- (void)setretweetText{
    
//    self.retweetText = [NSString stringWithFormat:@"@%@:%@",self.status.retweeted_status.user.name,self.status.retweeted_status.text];
    
    if (self.status.retweeted_status.text) {
        
        self.retweetAttributString = [self attributeText:self.status.retweeted_status.text];
        
    }else{
        
        self.retweetAttributString = [self attributeText:@""];
        
    }
}

- (void)setMemberImage{
    
    int value = self.status.user.mbrank.intValue;
    
    
        if (value > 0 && value < 7 ) {
            
            self.memberImage = [NSString stringWithFormat:@"common_icon_membership_level%d",value];
            
        }

    
  
}

@end
